﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;

namespace Util
{
    public static class Extensions
    {
        /// <summary>
        /// List转化为DataSet
        /// </summary>
        /// <typeparam name="T">泛型类</typeparam>
        /// <param name="list">列表</param>
        /// <returns>DataSet数据集</returns>
        public static DataSet ToDataSet<T>(this IList<T> list)
        {
            Type elementType = typeof(T);
            var ds = new DataSet();
            var t = new DataTable();
            ds.Tables.Add(t);
            elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
            foreach (T item in list)
            {
                var row = t.NewRow();
                elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
                t.Rows.Add(row);
            }
            return ds;
        }

        /// <summary>
        /// 重写Format，参数为List 类型，扩展了传统的 param 参数
        /// </summary>
        /// <param name="format">格式化字符串</param>
        /// <param name="list">格式化字符串需要的参数</param>
        /// <returns>格式化后的参数</returns>
        public static string Format(this string format, IList<string> list)
        {
            for (int i = 0; i < list.Count; i++)
            {
                format = format.Replace("{" + i.ToString() + "}", list[i]);
            }
            return format;
        }

        /// <summary>
        /// 将BitArray显示为字符串
        /// </summary>
        /// <param name="arr">位数组</param>
        /// <returns>由01组成的字符串</returns>
        public static string ToBinString(this BitArray arr)
        {
            StringBuilder buf = new StringBuilder();
            foreach (bool bit in arr)
            {
                buf.Append(bit ? 1 : 0);
            }
            return buf.ToString();
        }

        public static bool IsEqual(this List<string> list_1, List<string> list_2)
        {
            if (list_1 == null || list_2 == null || list_1.Count == 0 || list_2.Count == 0)
                return false;

            if (list_1.Count != list_2.Count)
                return false;

            for (int i = 0; i < list_1.Count; i++)
            {
                if (list_1[i] != list_2[i])
                    return false;
            }
            return true;
        }

        //从第start 到 第end 个元素
        public static string[] SubArray(this string[] array, int start, int end)
        {
            List<string> list = new List<string>();
            for (int i = start; i <= end; i++)
            {
                list.Add(array[i].Trim());
            }
            return list.ToArray();
        }
    }
}
